<?php

namespace App\Http\Services;

use App\Http\Model\FinanceDiamond;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\WishDefender;
use Exception;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\Hint;
use App\Http\Model\User;
use App\Http\Model\Gift;
use App\Http\Model\GiftBag;
use App\Http\Model\LuckDraw;
use App\Http\Model\Mall;
use App\Http\Model\Room;
use App\Http\Model\RoomHot;
use App\Http\Model\System;
use App\Model\FinanceWallet;
use App\Modules\LuckDraw\Models\UserPropLogModel;
use App\Modules\LuckDraw\Models\UserPropModel;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class WishDefenderServices extends CommonServices
{
    protected $userModel;
    protected $giftModel;
    protected $wishDefenderModel;
    protected $customService;
    protected $giftBag_model;
    protected $systemModel;
    protected $msgService;
    protected $financeUserWallet;
    protected $FinanceDiamond;
    protected $userPropModel;
    protected $userPropLogModel;
    protected $mall_model;
    protected $luckId;
    protected $roomHotModel;

    protected $allProgressValue = 'DEFENDER:PROGRESS:VALUE';//全服进度值
    protected $defenderLuckId = 'DEFENDER:LUCKID';//当前池子id
    protected $defenderEndTime = 'DEFENDER:ENDTIME';//结束时间 秒

    // 成为擂主价格
    protected $winnerGiftPrice = 6660;

    public function __construct()
    {
        parent::__construct();

        $this->userModel = new User();
        $this->giftModel = new Gift();
        $this->wishDefenderModel = new WishDefender();
        $this->customService = new CustomServices();
        $this->giftBag_model = new GiftBag();
        $this->systemModel = new System();
        $this->financeUserWallet = new FinanceUserWallet();
        $this->msgService = new MsgServices();
        $this->FinanceDiamond = new FinanceDiamond();
        $this->userPropModel = new UserPropModel();
        $this->userPropLogModel = new UserPropLogModel();
        $this->mall_model = new Mall();
        $this->roomHotModel = new RoomHot();
        $this->luckId = 1000;
    }

    /**
     * 星辰变全服中奖记录列表
     */
    public function winnerList($page, $limit)
    {
        $data = [];
        do {
            $list = $this->wishDefenderModel->awardListV2($page, $limit, []);

            $listEx = [];
            if (!empty($list)) {
                $userIds = array_column($list, 'user_id');
                $userList = $this->userModel->getUserInfoByIds($userIds);
                $userList = array_column($userList, null, 'user_id');

                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'image', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach ($list as $key => $val) {
                    $newArr = [];
                    if (empty($userList[$val['user_id']])) {
                        continue;
                    }
                    if (empty($giftList[$val['gift_id']])) {
                        continue;
                    }
                    $newArr['userId'] = $val['user_id'];
                    $newArr['giftId'] = $val['gift_id'];
                    $newArr['name'] = $giftList[$val['gift_id']]['name'];
                    $newArr['price'] = $giftList[$val['gift_id']]['price'];
                    $newArr['createdAt'] = $val['created_at'];
                    $newArr['nickname'] = $userList[$val['user_id']]['nickname'];
                    $newArr['uuid'] = $userList[$val['user_id']]['uuid'];
                    $newArr['avatar'] = build_image(json_decode($userList[$val['user_id']]['portrait'], true)[0]);
                    $newArr['image'] = build_image($giftList[$val['gift_id']]['image']);
                    $newArr['luck_id'] = $val['pool_level'];

                    $listEx[] = $newArr;
                }
            }


            $data = $listEx;
        } while (false);

        return $data;
    }


    /**
     * 星辰变池子外显概率列表
     */
    public function poolAwardListV2($luckId)
    {
        $data = [];
        do {
            if (empty($luckId)) {
                break;
            }
            $list = $this->wishDefenderModel->getWishLuckGift($luckId);

            $listEx = [];
            if(!empty($list)) {
                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds,['gift_id','name','image','price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach($list as $key=>$val) {
                    if(empty($giftList[$val['gift_id']])) {
                        continue;
                    }
                    $item = [];
                    $item['gift_id'] = $val['gift_id'];
                    $item['name'] = $giftList[$val['gift_id']]['name'];
                    $item['price'] = $giftList[$val['gift_id']]['price'];
                    $item['image'] = build_image($giftList[$val['gift_id']]['image']);
                    $listEx[] = $item;
                }
            }

            $data = $listEx;
//按照排序的，序号1排第一个
//            usort($data, function ($a, $b) {
//                return $b['price'] <=> $a['price'];
//            });
        } while (false);
        return $data;
    }

    /**
     * 抽奖
     */
    public function draw($userId, $num, $roomId, $luckId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $now = time();
        do {
            //获取目前奖池
//            $progressInfo = $this->getProgess();
            $currentLuckId = $this->getLuckId();
            if($luckId != $currentLuckId){
                $code = Hint::DEFENDER_POOL_CHANGE;
                $data['luck_id'] = $currentLuckId;
                break;
            }
            $num = abs($num);
            //配置
            $config = $this->wishDefenderModel->getWishDefenderConfig();
            if (empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            $oneNum = $config['need_num'];

            $needNum = $oneNum * $num;

            //个人池用户
            $poolUser = $this->wishDefenderModel->getPoolUser($userId, $luckId);

            //获取用户当前抽奖的奖池
            //奖池
            $pool = $this->wishDefenderModel->getPool($luckId);
            $basePoolList = []; //普通池的
            $userPoolList = []; //用户个人池的
            foreach ($pool as $val) {
                if ($val['status'] != 1) {
                    continue;
                }
                //奖池配置数据
                $poolConfig = $this->wishDefenderModel->getWishLuckPoolConfig($val['id']);
                if (empty($poolConfig)) {
                    write_log('error_wishdefender', '$poolConfig empty', ['pool_id' => $val['id']]);
                    continue;
                }
                $val['poolConfig'] = $poolConfig;
                //普通池
                if ($val['pool_type'] == 1) {
                    $basePoolList[] = $val;
                }
                //用户个人池
                if (in_array($val['pool_type'], [2, 3])) {
                    if (!empty($poolUser) && !empty($poolUser['pool_id']) && $val['id'] == $poolUser['pool_id']) {
                        $userPoolList[] = $val;
                    }
                }
            }

            $poolList = []; //已开启的奖池
            $giftToItemNo = []; //奖池礼物对应的奖池序号
            $ifdrawInUserPool = 0; //是否在个人池抽奖 0=否 1=是
            if (!empty($poolUser) && !empty($userPoolList)) {
                $poolList = $userPoolList;
                $ifdrawInUserPool = 1;
            } else {
                $poolList = $basePoolList;
            }
            if (empty($poolList)) {
                $code = Hint::WAIT_OPEN;
                break;
            }
            $giftToItemNo = array_column($poolList[0]['poolConfig'], 'item_no', 'gift_id');

            //搜神卡价格
            $luckDrawInfo = $this->wishDefenderModel->luckDrawInfo(1000);
            $luckDrawPrice = empty($luckDrawInfo['price']) ? 0 : $luckDrawInfo['price'];

            //用户搜神卡数量
            $userLuckDrawProp = $this->wishDefenderModel->getAvail(1000, $userId);
            if ($userLuckDrawProp < $needNum) {
                $code = Hint::LUCK_DRAW_PROP_NOT_ENOUGH;
                $msg = '搜神卡数量不足';
                break;
            }

            //扣搜神卡
            $decrRes = $this->wishDefenderModel->decrUniverseTickerUserProp($userId, 1000, $needNum);
            if (!$decrRes) {
                $code = Hint::LUCK_DRAW_PROP_NOT_ENOUGH;
                $msg = '搜神卡数量不足';
                break;
            }

            //用户信息
            $userInfo = $this->userModel->get_users_by_ids([$userId]);
            $userInfo = array_column($userInfo, null, 'user_id');
            $userInfo = $userInfo[$userId];

            //用户总抽奖记录数
            if ($ifdrawInUserPool) {
                //个人池用户
                $drawNumNow = $drawNum = $poolUser['draw_num'];
            } else {
                //普通
                $drawNumNow = $drawNum = $this->wishDefenderModel->getUserWishLuckDrawNumByWeek($userId, $luckId);
            }

            //白名单
            $whiteListNow = $whiteList = $this->wishDefenderModel->getWishLuckWhite($userId, $luckId);
            //订单记录
            $orderInfo = [
                'user_id' => $userId,
                'num' => $num,
                'prop_num' => $needNum,
                'prop_diamond_num' => $needNum * $luckDrawPrice,
                'reward_diamond_num' => 0,
                'pool_level' => $luckId,
                'created_at' => date('Y-m-d H:i:s', $now),
            ];
            $orderId = $this->wishDefenderModel->addWishLuckOrder($orderInfo);
            if (empty($orderId)) {
                $code = Hint::ERR_SYS_FAIL;
                break;
            }

            //抽奖
            $drawLogList = [];
            try {
                for ($i = 1; $i <= $num; $i++) {
                    $drawNumNow = $drawNumNow + 1;
                    $drawLog = [];
                    $drawLog['draw_no'] = $i;
                    $drawLog['gift_id'] = 0;
                    $drawLog['white_id'] = 0;
                    $drawLog['pool_id'] = 0;
                    $drawLog['item_no'] = 0;
                    //白名单
                    if (!empty($whiteListNow)) {
                        $whiteInfo = array_shift($whiteListNow);
                        $drawLog['gift_id'] = $whiteInfo['gift_id'];
                        $drawLog['white_id'] = $whiteInfo['id'];
                        $drawLog['item_no'] = empty($giftToItemNo[$whiteInfo['gift_id']]) ? 11 : $giftToItemNo[$whiteInfo['gift_id']];
                    } else {
                        $usePool = []; //使用的奖池
                        //在范围的
                        foreach ($poolList as $val) {
                            if ($val['min_num'] <= $drawNumNow && $drawNumNow <= $val['max_num']) {
                                $usePool = $val;
                            }
                        }
                        //上一个
                        $prevNum = 0;
                        if (empty($usePool)) {
                            foreach ($poolList as $val) {
                                if ($val['max_num'] <= $drawNumNow && $prevNum <= $val['max_num']) {
                                    $usePool = $val;
                                    $prevNum = $val['max_num'];
                                }
                            }
                        }
                        //下一个
                        $nextNum = 0;
                        if (empty($usePool)) {
                            foreach ($poolList as $val) {
                                if ($val['min_num'] >= $drawNumNow && ($nextNum == 0 || $nextNum >= $val['min_num'])) {
                                    $usePool = $val;
                                    $nextNum = $val['min_num'];
                                }
                            }
                        }
                        //还是没有取第一个
                        if (empty($usePool)) {
                            $usePool = $poolList[0];
                        }

                        //抽取
                        if (in_array($usePool['pool_type'], [2, 3])) {
                            //个人池
                            $poolConfigId = $this->wishDefenderModel->drawWishLuckUser($luckId, $usePool['id'], $userId);
                        } else {
                            //普通
                            $poolConfigId = $this->wishDefenderModel->drawWishLuck($luckId, $usePool['id']);
                        }
                        $poolConfigMap = array_column($usePool['poolConfig'], null, 'id');

                        $drawLog['gift_id'] = $poolConfigMap[$poolConfigId]['gift_id'] ?? 0;
                        $drawLog['white_id'] = 0;
                        $drawLog['pool_id'] = $poolConfigMap[$poolConfigId]['pool_id'];
                        $drawLog['item_no'] = $poolConfigMap[$poolConfigId]['item_no'];
                    }

                    $drawLogList[] = $drawLog;
                }
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                write_log('error_wishdefender', 'wishLuckDraw 抽奖失败', ['orderId' => $orderId, 'message' => $e->getMessage(), 'line' => $e->getLine()]);
                break;
            }

            //累加用户总抽奖记录数
            $this->wishDefenderModel->incrUserDrawWeekNum($userId, $num, $luckId);

            $giftIds = array_column($drawLogList, 'gift_id');
            $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price', 'image']);
            $giftList = array_column($giftList, null, 'gift_id');

            //抽奖保存
            DB::beginTransaction();
            try {
                $rewardDiamondNumAll = 0;
                //新增星辰变抽奖记录
                foreach ($drawLogList as $key => $val) {
                    $giftPrice = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];

                    $val['order_id'] = $orderId;
                    $val['user_id'] = $userId;
                    $val['prop_num'] = $config['need_num'];
                    $val['gift_num'] = 1;
                    $val['prop_diamond_num'] = $val['prop_num'] * $luckDrawPrice;
                    $val['reward_diamond_num'] = $giftPrice;
                    $val['created_at'] = date('Y-m-d H:i:s', $now);
                    $val['pool_level'] = $luckId;
                    $this->wishDefenderModel->addWishLuckDraw($val);

                    //奖励价值钻石数
                    $rewardDiamondNumAll = $rewardDiamondNumAll + $val['reward_diamond_num'];

                    //白名单
                    if (!empty($val['white_id'])) {
                        $this->wishDefenderModel->updateWishLuckWhite($val['white_id'], $orderId);
                    }

                    //送礼物
                    $this->giftBag_model->inc((int)$userId, 0, (int)$val['gift_id'], 1, $luckId + 3000);

                    // 擂主
                    $ifLock = false;
                    if ($giftPrice >= $this->winnerGiftPrice) {
                        for ($i = 0; $i < 5; $i++) {
                            $ifLock = redis_lock($this->wishDefenderModel->countdownLock, 3);
                            if ($ifLock) {
                                break;
                            } else {
                                usleep(500000);//0.5s
                            }
                        }

                        $this->wishDefenderModel->setWinner($userId);

                        if ($ifLock) {
                            redis_unlock($this->wishDefenderModel->countdownLock);
                        }

                        $this->msgService->defenderChangeWinnerMsg(['winner_name' => $userInfo['nickname'], 'winner_avatar' => $userInfo['thumbnails'][0]]);
                    }

                    $drawLogList[$key] = $val;
                }
                $endTime = date('Y-m-d H:i:s', time()+1);
                //更新订单
                $this->wishDefenderModel->updateWishLuckDraw($orderId, $rewardDiamondNumAll, $endTime);
                //更新个人池用户记录
                if ($ifdrawInUserPool && $val['white_id'] == 0) {
                    $this->wishDefenderModel->updateWishLuckUserPoolLog($poolUser['id'], $orderInfo['prop_diamond_num'], $rewardDiamondNumAll, $orderInfo['num']);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_wishdefender', 'wishLuckDraw 抽奖保存', ['orderId' => $orderId, 'drawLogList' => $drawLogList, 'message' => $e->getMessage(), 'line' => $e->getLine()]);
                break;
            }
            //更新星辰变用户每日抽奖数据统计缓存
//            $this->wishDefenderModel->updateWishLuckUserDay($luckId, $userId, $orderInfo['prop_diamond_num'], $rewardDiamondNumAll, $orderInfo['num']);

            //更新搜身次数
            Redis::INCRBYFLOAT($this->wishDefenderModel->allProgressValue, $num);

            //汇总返回值
            $resList = $this->wishDefenderModel->getDrawList($orderId);
            $giftType = 1;
            foreach ($resList as $k=>$vals) {
                $item = [];
                if($val['pool_level'] == 1001){
                    $giftType = 2;
                } elseif ($val['pool_level'] == 1002) {
                    $giftType = 3;
                } elseif ($val['pool_level'] == 1003) {
                    $giftType = 4;
                }
                $item['type'] = $giftType;
                $item['luckId'] = $val['pool_level'];
                $item['userId'] = $userId;
                $item['awardId'] = $orderId;
                $item['timeLimit'] = 0;
                $item['name'] = empty($giftList[$vals['gift_id']]['name']) ? '' : $giftList[$vals['gift_id']]['name'];
                $item['price'] = (int) (empty($giftList[$vals['gift_id']]['price']) ? 0 : $giftList[$vals['gift_id']]['price']);
                $item['image'] = empty($giftList[$vals['gift_id']]['image']) ? '' : build_image($giftList[$vals['gift_id']]['image']);
                $item['nickname'] = $userInfo['nickname'];
                $item['num'] = $vals['gift_num'];
                $resList[$k] = $item;
            }
            $resList = array_values($resList);
            array_multisort(array_column($resList, 'price'), SORT_DESC, $resList);

            //房间内游戏公屏游戏消息
            if ($roomId > 10) {
                // 飘屏 查询飘屏中设置的飘屏限制钻石数,因为公屏限制和飘屏限制一致
                $laceName = '万神殿';
                if($luckId == 1000){
                    $laceName .= '-1阶段';
                } elseif ($luckId == 1001){
                    $laceName .= '-2阶段';
                } elseif ($luckId == 1002){
                    $laceName .= '-3阶段';
                } elseif ($luckId == 1003){
                    $laceName .= '-4阶段';
                    $rapidMode = Redis::get($this->wishDefenderModel->rapidMode);
                    if ($rapidMode == 1) {
                        $laceName = '万神殿-无限乱斗';
                    }
                }

                $screenId = $this->getFullScreenId($luckId);
                $fullScreen = $this->systemModel->getFullScreen($screenId);

                foreach ($resList as $val) {
                    if(!empty($fullScreen) && $val['price'] >= 980) {
                        $this->msgService->defenderWorldMsg(['nickname' => $userInfo['nickname'], 'user_id' => $userInfo['user_id'], 'placeName' => $laceName, 'giftName' => $val['name'], 'giftPrice' => $val['price'], 'giftNum' => $val['num'], 'giftImg' => $val['image']]);
                    }
                    if($val['price']>=250){
                        //$this->msgService->defenderRoomMsg($roomId, ['nickname' => $userInfo['nickname'], 'user_id' => $userInfo['user_id'], 'placeName' => $laceName, 'giftName' => $val['name'], 'giftPrice' => $val['price'], 'giftNum' => $val['num'], 'giftImg' => $val['image']]);
                    }
                }
            }

            $data['list'] = $resList;
            $data['order_id'] = $orderId;
            $data['reward_diamond_num'] = $rewardDiamondNumAll;
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 飘屏处理
     */
    public function wishLuckDrawFull($orderId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $luckId = 1000;
        $now = time();
        do {
            if (empty($orderId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $orderInfo = $this->wishDefenderModel->orderAwardList($orderId);
            if (empty($orderInfo)) {
                break;
            }
            //配置
            $config = $this->wishDefenderModel->getWishDefenderConfig();
            if (empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //用户信息
            $userInfo = $this->userModel->get_users_by_ids([$orderInfo['user_id']]);
            $userInfo = array_column($userInfo, null, 'user_id');
            $userInfo = $userInfo[$orderInfo['user_id']];

            $giftIds = array_column($orderInfo['drawList'], 'gift_id');
            $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price', 'image']);
            $giftList = array_column($giftList, null, 'gift_id');
            $sendDefender = [];
            //飘屏
            foreach ($orderInfo['drawList'] as $val) {
                $giftPrice = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                $giftName = empty($giftList[$val['gift_id']]['name']) ? 0 : $giftList[$val['gift_id']]['name'];
                //滚动公告
                $sendDefender[] = [
                    'user_name' => $userInfo['nickname'],
                    'user_head' => $userInfo['images'][0],
                    'gift_name' => $giftName,
                    'gift_num' => $val['gift_num']
                ];

                //普通池/高级池不同飘屏
                $screenId = $this->getFullScreenId($val['pool_level']);
                $this->msgService->sendFullScreen($screenId, null, ['userName' => $userInfo['nickname'], 'diamondNum' => $giftPrice, 'giftName' => $giftName, 'giftNum' => $val['gift_num']], [], ['giftPrice' => $giftPrice]);
            }

            //发送滚动中奖
            $this->msgService->sendDefender($sendDefender);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 获取活动规则
     */
    public function getRule()
    {
        $config = $this->wishDefenderModel->getWishDefenderConfig();
        if (empty($config)) {
            return [];
        }
        $data = [];
        $data['play_rule'] = $config['rule'];
        return $data;
    }

    /**
     * 兑换搜神卡
     */
    public function exchange($num, $userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $luckId = 1000;
        do {
            //获取所需钻石总额
            $luckDrawInfo = $this->wishDefenderModel->luckDrawInfo($luckId);
            $luckDrawPrice = empty($luckDrawInfo['price']) ? 200 : $luckDrawInfo['price'];
            $needTotalDiamond = $luckDrawPrice * $num;
            //查询当前用户可用钻石
            $walletData = $this->financeUserWallet->get_wallet($userId);
            if ($walletData['diamond_balance'] < $needTotalDiamond) {
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            DB::beginTransaction();
            try {
                //扣除钻石
                $this->FinanceDiamond->inc($userId, 0, 0, 6, -$needTotalDiamond, '兑换搜神卡');
                //增加道具
                $ok = $this->wishDefenderModel->addTiket($luckId, $userId, $num);
                //道具保存成功则增加日志
                if ($ok) {
                    $ok = $this->wishDefenderModel->addTiketLog($luckId, $userId, 1000, $num);
                }
                // 赠送头像框
                $goodId = 150;
                $goodInfo = $this->mall_model->getMallGoodByGoodsId($goodId);
                if (empty($goodInfo)) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $skuList = $this->mall_model->getSkuDataByGoods($goodId);
                if (empty($skuList[0])) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $goodMap[$goodId]['goods_name'] = $goodInfo['goods_name'];
                $goodMap[$goodId]['goods_type'] = $goodInfo['goods_type'];
                $goodMap[$goodId]['sku_id'] = $skuList[0]['sku_id'];
                //有效期
                $timeLimit = $num * 3600;
                //商品增加
                $this->mall_model->shoppingAct(
                    11,
                    $userId,
                    $goodId,
                    $goodMap[$goodId]['goods_name'],
                    $goodMap[$goodId]['goods_type'],
                    $goodMap[$goodId]['sku_id'],
                    $timeLimit,
                    0,
                    $timeLimit,
                    time(),
                    2
                );
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_wishdefender', 'error 兑换恋爱卡', ['msg' => $e->getMessage(), 'line' => $e->getLine()]);
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            $walletData = $this->financeUserWallet->get_wallet($userId);
            $diamonNum = $walletData['diamond_balance'];
            $propNum = $this->wishDefenderModel->getAvail($luckId, $userId);
            $data = [
                'diamond' => $diamonNum,
                'prop' => $propNum
            ];
        } while (false);
        return compact('code', 'data', 'msg');
    }


    /**
     * 获取资产信息
     */
    public function balance($userId)
    {
        $luckId = 1000;
        $propNum = $this->wishDefenderModel->getAvail($luckId, $userId);
        $data = [
            'prop' => $propNum,
        ];
        return $data;
    }

    /**
     * 获取用户抽奖记录
     */
    public function wishLuckAwardListByUserId($page, $limit, $userId)
    {
        $data = [];
        do {
            $where = [];
            //今天
            $where['user_id'] = $userId;
            $list = $this->wishDefenderModel->wishLuckAllAwardList($page, $limit, $where);
            $listEx = [];
            if (!empty($list)) {
                $userIds = array_column($list, 'user_id');
                $userList = $this->userModel->get_users_by_ids($userIds);
                $userList = array_column($userList, null, 'user_id');

                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'image', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');
                $newArr = [];
                foreach ($list as $key => $val) {
                    if (empty($userList[$val['user_id']])) {
                        continue;
                    }
                    if (empty($giftList[$val['gift_id']])) {
                        continue;
                    }
                    $newArr['userId'] = $val['user_id'];
                    $newArr['giftId'] = $val['gift_id'];
                    $newArr['name'] = $giftList[$val['gift_id']]['name'];
                    $newArr['price'] = $giftList[$val['gift_id']]['price'];
                    $newArr['num'] = $val['gift_num'];
                    $newArr['createdAt'] = $val['created_at'];
                    $newArr['nickname'] = $userList[$val['user_id']]['nickname'];
                    $newArr['uuid'] = $userList[$val['user_id']]['user_uid'];
                    $newArr['avatar'] = build_image($userList[$val['user_id']]['images'][0]);
                    $newArr['image'] = build_image($giftList[$val['gift_id']]['image']);
                    $newArr['luck_id'] = $val['pool_level'];
                    $listEx[] = $newArr;
                }
            }
            $data = $listEx;
            unset($listEx);
        } while (false);

        return $data;
    }

    /**
     * 获取单次抽奖价格
     */
    public function getPrice($luckId)
    {
        $luckDrawInfo = $this->wishDefenderModel->luckDrawInfo($luckId);
        $luckDrawPrice = empty($luckDrawInfo['price']) ? 0 : $luckDrawInfo['price'];
        return ['price' => $luckDrawPrice];
    }

    /**后台配置 */


    /**
     * 星辰变每日统计
     */
    public function statisticalData($ymd, $poolLevel)
    {
        do {
            $dateSt = date('Y-m-d 00:00:00', strtotime($ymd));
            $dateEt = date('Y-m-d 23:59:59', strtotime($ymd));
            $info = $this->wishDefenderModel->wishPoolStatistics($dateSt, $dateEt, $poolLevel);

            $data = [];
            $data['ymd'] = date('Ymd', strtotime($ymd));
            $data['user_num'] = empty($info['user_num']) ? 0 : $info['user_num'];
            $data['draw_num'] = empty($info['draw_num']) ? 0 : $info['draw_num'];
            $data['prop_num'] = empty($info['prop_num']) ? 0 : $info['prop_num'];
            $data['prop_diamond_num'] = empty($info['prop_diamond_num']) ? 0 : $info['prop_diamond_num'];
            $data['reward_diamond_num'] = empty($info['reward_diamond_num']) ? 0 : $info['reward_diamond_num'];
            $data['pool_level'] = $poolLevel;
            $data['profit_loss'] = $data['prop_diamond_num'] - $data['reward_diamond_num'];

            $this->wishDefenderModel->addWishPoolStatistics($data);
        } while (false);

        return $data;
    }

    //获取星辰变搜神卡价格
    public function getUniversePrice(){
        $luckDrawInfo = $this->wishDefenderModel->luckDrawInfo(1000);
        $luckDrawPrice = empty($luckDrawInfo['price']) ? 200 : $luckDrawInfo['price'];
        return $luckDrawPrice;
    }

    public function getLuckId() {
        $luckId = (int)Redis::get($this->wishDefenderModel->defenderLuckId);
        $luckId = empty($luckId) ? 1000 : $luckId;
        return $luckId;
    }

    public function getCountdownMode() {
        $countdownMode = Redis::get($this->wishDefenderModel->countdownMode);
        return $countdownMode ?: 0;
    }

    //获取全服进度信息
    public function getProgess(){
        $countdownInfo = $this->getCountdownInfo();

        // 当前阶段晋级下一阶段所需进度值，当前阶段幸运礼物
        $luckConfig = $this->wishDefenderModel->getStageInfo($countdownInfo['luck_id']);
        $luckGift = $this->giftModel->get_gift($luckConfig['gift_id']);

        $luckName = $this->wishDefenderModel->getLuckName($countdownInfo['luck_id']);
        $rapidMode = Redis::get($this->wishDefenderModel->rapidMode);
        if ($rapidMode == 1) {
            $luckName = '无限乱斗圣战奖励';
        }

        $return = [
            'luck_id' => $countdownInfo['luck_id'],
            'luck_name' => $luckName,
            'winner_name' => $countdownInfo['winner_name'],
            'winner_avatar' => $countdownInfo['winner_avatar'],
            'end_time' => $countdownInfo['end_time'],
            'end_minutes' => $countdownInfo['end_minutes'],
            'end_seconds' => $countdownInfo['end_seconds'],
            'start' => $countdownInfo['start'],
            'gift_name' => $luckGift['name'] ?: '',
            'gift_img' => $luckGift['image'] ?: '',
            'gift_price' => $luckGift['price'] ?: 0,
            'limit' => $luckConfig['limit'],
        ];

        return $return;
    }

    public function getCountdownInfo() {
        //获取当前抽奖id
//        $luckId = (int)Redis::get($this->wishDefenderModel->defenderLuckId);
//        $luckId = empty($luckId) ? 1000 : $luckId;
        $luckId = $this->getLuckId();

        $luckEndTime = $this->wishDefenderModel->getWinnerCountdown();
        $endMinutes = '00';
        $endSeconds = '00';
        if(!empty($luckEndTime)){
            $endTime = $this->secondsToTime($luckEndTime);
            $endMinutes = $endTime['minutes'];
            $endSeconds = $endTime['seconds'];
        }

        $winnerName = '';
        $winnerAvatar = '';
        $winnerUid = $this->wishDefenderModel->getWinner();
        if (!empty($winnerUid)) {
            $userInfo = $this->userModel->get_users_by_ids([$winnerUid]);
            $userInfo = array_column($userInfo, null, 'user_id');
            $userInfo = $userInfo[$winnerUid];
            $winnerName = $userInfo['nickname'];
            $winnerAvatar = $userInfo['thumbnails'][0];
        }

        //进度
        $allStart = Redis::get($this->wishDefenderModel->allProgressValue) ?: 0;

        $return = [
            'luck_id' => $luckId,
            'winner_name' => $winnerName,
            'winner_avatar' => $winnerAvatar,
            'end_time' => $luckEndTime,
            'end_minutes' => $endMinutes,
            'end_seconds' => $endSeconds,
            'start' => (int)$allStart,
        ];

        return $return;
    }

    public function secondsToTime($seconds) {
        $minutes = floor($seconds / 60); // 取整得分钟数
        $seconds = $seconds % 60; // 取余得剩余秒数

        return [
            'minutes' => str_pad($minutes, 2, '0', STR_PAD_LEFT),
            'seconds' => str_pad($seconds, 2, '0', STR_PAD_LEFT),
        ];
    }


    public function getFullScreenId($luckId) {
        $fullScreenId = 71;
        if($luckId == 1000){
            $fullScreenId = 71;
        }else{
            $fullScreenId = 71;
        }

        return $fullScreenId;
    }

    // 擂主倒计时处理
    public function winnerCountdownHandle() {
        // 倒计时结束
        //Redis::set($this->wishDefenderModel->winnerCountdown, 20);
        // 清空已抽取次数
        //Redis::set($this->wishDefenderModel->allProgressValue, 0);
        // 清空增加计时次数
        //Redis::set($this->wishDefenderModel->winnerIncrNum, 0);

        do{
            $countdown = $this->wishDefenderModel->getWinnerCountdown();
            if ($countdown >= 1) {
                //获取当前抽奖id
                $luckId = $this->getLuckId();

                // 当前阶段配置
                $luckConfig = $this->wishDefenderModel->getStageInfo($luckId);

                //进度
                $allStart = Redis::get($this->wishDefenderModel->allProgressValue) ?: 0;

                $endMinutes = '00';
                $endSeconds = '00';
                if(!empty($countdown)){
                    $endTime = $this->secondsToTime($countdown);
                    $endMinutes = $endTime['minutes'];
                    $endSeconds = $endTime['seconds'];
                }

                $luckName = $this->wishDefenderModel->getLuckName($luckId);

                $countdownInfo = [
                    'luck_id' => $luckId,
                    'luck_name' => $luckName,
                    'end_time' => $countdown,
                    'end_minutes' => $endMinutes,
                    'end_seconds' => $endSeconds,
                    'start' => (int)$allStart,
                ];

                if ($allStart >= $luckConfig['limit'] && $luckId < 1003) {
                    if ($luckId == 1000) {
                        $countdownMode = $this->getCountdownMode();
                        if ($countdownMode == 0) {
                            // 手数从0开始
                            Redis::set($this->wishDefenderModel->allProgressValue, 0);
                            // 变成倒计时模式
                            Redis::set($this->wishDefenderModel->countdownMode, 1);
                            continue;
                        }
                    }

                    // 升阶段
                    $newLuckId = $luckId + 1;
                    $newLuckName = $this->wishDefenderModel->getLuckName($newLuckId);

                    $winnerName = '';
                    $winnerAvatar = '';
                    $winnerUid = $this->wishDefenderModel->getWinner();
                    if (!empty($winnerUid)) {
                        $userInfo = $this->userModel->get_users_by_ids([$winnerUid]);
                        $userInfo = array_column($userInfo, null, 'user_id');
                        $userInfo = $userInfo[$winnerUid];
                        $winnerName = $userInfo['nickname'];
                        $winnerAvatar = $userInfo['thumbnails'][0];
                    }

                    // 新阶段礼物
                    $newLuckConfig = $this->wishDefenderModel->getStageInfo($newLuckId);
                    $newLuckGift = $this->giftModel->get_gift($newLuckConfig['gift_id']);

                    // 外显奖池礼物
                    $giftList = $this->poolAwardListV2($newLuckId);

                    // 设置新阶段
                    Redis::set($this->wishDefenderModel->defenderLuckId, $newLuckId);
                    Redis::set($this->wishDefenderModel->allProgressValue, 0);

                    // 升下一阶段
                    $changePoolData = [
                        'new_luck_id' => $newLuckId,
                        'new_luck_name' => $newLuckName,
                        'winner_name' => $winnerName,
                        'winner_avatar' => $winnerAvatar,
                        'gift_name' => $newLuckGift['name'] ?: '',
                        'gift_img' => $newLuckGift['image'] ?: '',
                        'gift_price' => $newLuckGift['price'] ?: 0,
                        'end_minutes' => $endMinutes,
                        'end_seconds' => $endSeconds,
                        'limit' => (int)$newLuckConfig['limit'],
                        'start' => 0,
                        'gift_list' => $giftList,
                    ];

                    $this->msgService->defenderChangePoolMsg($changePoolData);

                    sleep(1);

                } else {
                    if ($allStart >= $luckConfig['limit'] && $luckId == 1003) {
                        // 变成无限乱斗模式
                        Redis::set($this->wishDefenderModel->rapidMode, 1);
                        // 手数从0开始
                        Redis::set($this->wishDefenderModel->allProgressValue, 0);
                        $countdownInfo['luck_name'] = '无限乱斗圣战奖励';
                    } else {
                        if ($luckId == 1003) {
                            $rapidMode = Redis::get($this->wishDefenderModel->rapidMode);
                            if ($rapidMode == 1) {
                                $countdownInfo['luck_name'] = '无限乱斗圣战奖励';
                            }
                        }
                    }

                    // 倒计时IM
                    $this->msgService->defenderCountdownMsg($countdownInfo);

                    // 倒计时减1
                    $countdownMode = $this->getCountdownMode();
                    $winnerUid = $this->wishDefenderModel->getWinner();
                    if ($countdownMode == 1 && !empty($winnerUid)) {
                        $this->wishDefenderModel->decrWinnerCountdown();
                    }

                    sleep(1);
                }

            } else {
                // 加锁
                $ifLock = redis_lock($this->wishDefenderModel->countdownLock, 3);
                if (!$ifLock) {
                    usleep(200000);
                    continue;
                }

                $now = time();

                $countdown = $this->wishDefenderModel->getWinnerCountdown();
                if ($countdown != 0) {
                    // 解锁
                    redis_unlock($this->wishDefenderModel->countdownLock);
                    usleep(100000);//0.5s
                    continue;
                }

                // 倒计时重置
                Redis::set($this->wishDefenderModel->winnerCountdown, WishDefender::WINNER_INIT_TIME);

                // 倒计时结束，发放奖励，回到1阶段
                $winnerUid = $this->wishDefenderModel->getWinner();

                //获取当前抽奖id
                $luckId = $this->getLuckId();

                // 当前阶段配置
                $luckConfig = $this->wishDefenderModel->getStageInfo($luckId);

                //进度
                $allStart = Redis::get($this->wishDefenderModel->allProgressValue);
                $allStart = empty($allStart) ? 0 : $allStart;

                // 发擂主奖励
                if (!empty($winnerUid)) {
                    $this->giftBag_model->inc((int)$winnerUid, 0, (int)$luckConfig['gift_id'], 1, $luckId + 3010);

                    // 记擂主奖励数据表
                    $dWinnerData = [
                        'pool_level' => $luckId,
                        'user_id' => $winnerUid,
                        'gift_id' => $luckConfig['gift_id'],
                        'created_at' => date('Y-m-d H:i:s', $now),
                    ];
                    $this->wishDefenderModel->addWinner($dWinnerData);
                }

                // 结束当前阶段
                $this->wishDefenderModel->endStage();

                // 下一阶段
                $newLuckId = 1000;
//                if ($luckId >= 1003) {
//                    $newLuckId = 1000;
//                } else {
//                    if ($allStart >= $luckConfig['limit']) {
//                        $newLuckId = $luckId + 1;
//                    } else {
//                        if ($luckId <= 1000) {
//                            $newLuckId = 1000;
//                        } else {
//                            $newLuckId = $luckId - 1;
//                        }
//                    }
//                }

                // 设置新阶段
                Redis::set($this->wishDefenderModel->defenderLuckId, $newLuckId);

                // 新阶段礼物
                $newLuckConfig = $this->wishDefenderModel->getStageInfo($newLuckId);
                $newLuckGift = $this->giftModel->get_gift($newLuckConfig['gift_id']);

                // 倒计时
                $luckEndTime = $this->wishDefenderModel->getWinnerCountdown();
                $endMinutes = '00';
                $endSeconds = '00';
                if(!empty($luckEndTime)){
                    $endTime = $this->secondsToTime($luckEndTime);
                    $endMinutes = $endTime['minutes'];
                    $endSeconds = $endTime['seconds'];
                }

                // 外显奖池礼物
                $giftList = $this->poolAwardListV2($newLuckId);

                $newLuckName = $this->wishDefenderModel->getLuckName($newLuckId);

                $changePoolData = [
                    'new_luck_id' => $newLuckId,
                    'new_luck_name' => $newLuckName,
                    'winner_name' => '',
                    'winner_avatar' => '',
                    'gift_name' => $newLuckGift['name'] ?: '',
                    'gift_img' => $newLuckGift['image'] ?: '',
                    'gift_price' => $newLuckGift['price'] ?: 0,
                    'end_minutes' => $endMinutes,
                    'end_seconds' => $endSeconds,
                    'limit' => (int)$newLuckConfig['limit'],
                    'start' => 0,
                    'gift_list' => $giftList,
                ];

                $this->msgService->defenderChangePoolMsg($changePoolData);

                // 解锁
                redis_unlock($this->wishDefenderModel->countdownLock);

                sleep(1);
                break;

            }
        }while(true);

        return true;
    }
}
